package cn.jantd.modules.activiti.command;

import cn.jantd.modules.activiti.entity.Task;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.IdentityLinkType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: trial-training-flow-boot-parent
 * @Package: cn.jantd.modules.activiti.command
 * @ClassName: PreviousTask
 * @Author: admin
 * @Description:
 * @Date: 2020/10/30 16:56
 * @Version: 1.0
 */
public class PreviousTask implements Command{

        private String taskId;
        public PreviousTask(String taskId) {
            this.taskId = taskId;
        }
        public Object execute(CommandContext commandContext) {
            TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
            TaskEntity taskEntity = taskEntityManager.findTaskById(taskId);
            ExecutionEntity executionEntity = taskEntity.getExecution();

            String preActivityId =  executionEntity.getActivity().getIncomingTransitions().get(0).getSource().getId();

            String processDefinitionId = executionEntity.getProcessDefinitionId();
            ProcessDefinitionEntity processDefinitionEntity = Context.getProcessEngineConfiguration().getDeploymentManager()
                    .findDeployedProcessDefinitionById(processDefinitionId);
            ActivityImpl desActivity = processDefinitionEntity.findActivity(preActivityId);
            List list = new ArrayList();
            if(preActivityId.indexOf("Gateway") != -1 ){
                for (int i= 0;i<desActivity.getIncomingTransitions().size();i++){
                    Task task = new Task();
                    task.setId(desActivity.getIncomingTransitions().get(i).getSource().getId());
                    list.add(task);
                }
                return list;
            }
            Task task = new Task();
            task.setId(desActivity.getId());
            list.add(task);
            return list;
        }
    }

